<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2025/8/26} {18:23}
 */

namespace wanghua\general_utility_tools_php\kuaidi;

/**
 * 快递网，api查询逻辑类
 *
 * doc:
 * https://www.kuaidi.com/file.html
 */
class KuaidiService
{
    private string $apiUrl;
    private string $apiKey;

    public function __construct(string $apiUrl, string $apiKey = '')
    {
        $this->apiUrl = $apiUrl;
        $this->apiKey = $apiKey;
    }

    /**
     * 查询快递
     *
     * @param string      $trackingNumber 快递单号
     * @param string|null $companyCode    快递公司代码（可选）
     *
     * @return array 固定结构：
     *               [
     *                 'code' => 0 成功 / 非0 失败,
     *                 'msg'  => '错误描述',
     *                 'data' => 成功时返回原始 json 字符串，失败时为 null
     *               ]
     */
    public function query(string $trackingNumber, ?string $companyCode = null): array
    {
        $params = [
            'number' => $trackingNumber,
            'key'    => $this->apiKey,
        ];
        if ($companyCode !== null) {
            $params['company'] = $companyCode;
        }

        $url = $this->apiUrl . '?' . http_build_query($params);

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 10,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        $response = curl_exec($ch);

        // 发生 curl 错误
        if ($response === false) {
            $errno = curl_errno($ch);
            $error = curl_error($ch);
            curl_close($ch);
            return [
                'code' => $errno,
                'msg'  => $error,
                'data' => null,
            ];
        }

        curl_close($ch);

        return [
            'code' => 200,
            'msg'  => 'ok',
            'data' => $response,
        ];
    }
}